package com.jintoufs.web.action.common;



import com.jintoufs.domain.date.DateBean;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.service.date.DateBeanService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.util.date.DateUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimerTask;

public class AutoDateAction extends TimerTask {

    private static final SimpleDateFormat DATE_SDF = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private DateBeanService dateBeanService;
    @Resource
    private DictionaryService dictionaryService;

    @Override
    public void run() {
        int dateLength = 90;
        List<Dictionary> list = dictionaryService.getDicByKeyNo("SET_DATA_LENGTH");
        if (!list.isEmpty()) {
            dateLength = Integer.parseInt(list.get(0).getCaption());
        }
        DateBean dateBean = dateBeanService.getLast();
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        try {
            calendar1.setTime(DATE_SDF.parse(dateBean.getDate()));
            Integer num = DateUtils.dateDiff('d', calendar2,calendar1);
            for (; num<=dateLength; num++){
                String now = DateUtils.formatDate(num);
                if (!dateBeanService.isExist(now)){
                    dateBean = new DateBean();
                    dateBean.setDate(now);
                    dateBeanService.insert(dateBean);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
